// 目标：初始化 three.js 基础环境
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js'
export let scene, camera, renderer, controls, css3dRenderer, css2dRenderer

(function init() {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.z = 5
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)
})();

(function createControls() {
  controls = new OrbitControls(camera, renderer.domElement)
  controls.minPolarAngle = 0.25 * Math.PI
})();

(function createHelper() {
  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
})();

(function create2dRenderer () {
  // 创建一个2d的渲染器
  css2dRenderer = new CSS2DRenderer()
  css2dRenderer.setSize(innerWidth, innerHeight)
  css2dRenderer.domElement.style.position = 'fixed'
  css2dRenderer.domElement.style.left = '0'
  css2dRenderer.domElement.style.top = '0'
  css2dRenderer.domElement.style.pointerEvents = 'none'
  document.body.appendChild(css2dRenderer.domElement)
})();

(function resizeRender() {
  window.addEventListener('resize', () => {
    renderer.setSize(window.innerWidth, window.innerHeight)
    // 2d渲染器也要重新绘制
    css2dRenderer.setSize(window.innerWidth, window.innerHeight)
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
  })
})();


(function renderLoop() {
  renderer.render(scene, camera)
  // 2d渲染器渲染场景和摄像机
  css2dRenderer.render(scene, camera)
  controls.update()
  requestAnimationFrame(renderLoop)
})();